<template>
	<div class="w750" :class="themes.theme">
		<header :style="{ top: $route.meta.showHeadBox ? '44px' : '0px' }">
			<div class="header-box" :style="{ background: themes.color ? themes.color : '#fff' }">
				<div class="header-search" style="margin: 7px 10px">
					<input class="ser-input font-12" type="text" v-model="searchText" @keyup.enter="enterSearch('search', searchText)" placeholder="请输入商品关键词" />
					<i class="ser-i"></i>
					<img v-if="searchText" class="position-absolute w-16p text-ccc" style="right: 10px; top: 8px;" src="@/assets/images/close2.png" @click="clearInput" />
				</div>
				<div class="font-14 text-fff flex-center mr-1" @click="enterSearch('search', searchText)">搜索</div>
				<!-- <div class="header-mes" @click="enterSearch"><span class="mes-txt">搜索</span></div> -->
			</div>
		</header>
		<div class="search-touch">
			<!-- 热搜 -->
			<div class="hot-search">
				<div class="hot-content">
					<div class="hot-tit">历史记录</div>
					<i class="clear-icon" @click="clearKey"></i>
				</div>
				<div ref="parentDiv" class="hot-con">
					<template v-for="(item, index) in historySearch">
						<div
							v-if="(overNum&&!isExpand)?index<(historySearch.length - overNum - 1): true"
							class="item flex-center" :key="index"
							:ref="'history-item'+index"
							style="max-width: 40%;"
							@click="enterSearch('history', item.searchKey)"
						>
							<span class="line-clamp1">{{ item.searchKey }}</span>
						 </div>
					</template>
					<div v-show="overNum" class="back-img arrow transition-all05" :style="{transform: `rotate(${isExpand?'-270deg': '-90deg'})`}" @click="isExpand = !isExpand;">
						<img src="../../assets/images/back.png" alt="" />
					</div>
					<!-- <span v-show="isShowButton">></span> -->
				</div>
			</div>
			<!-- 热搜 -->
		</div>

		<div class="search-touch">
			<van-list
				v-if="!paging.emptylist"
			    v-model="paging.loading"
			    :finished="paging.finished"
			    finished-text="没有更多了"
			    @load="onLoad"
			    :immediate-check="false"
			    :error.sync="paging.error"
			    error-text="请求失败，点击重新加载"
			>
				<!-- 横向列表 -->
				<div class="pro-list" style="background: #f6f7f8">
					<ProList
						@myEvent="goProdDetail"
						:parmas="item"
						:pic="item.pic"
						:name="item.name"
						:money="item.price"
						v-for="(item, index) in jdList"
						:key="index"
						:isShowDis="false"
					></ProList>
				</div>
			</van-list>
			<Noempty :pic="require('@/assets/images/goods-empty.png')" :title="title" v-if="paging.emptylist && !paging.error" />
		</div>
	</div>
</template>

<script>
import { externalProd, getHistory, deleteHistory, getProdList, getAuth } from 'api/externalSearch';
import ProList from 'components/proList/proList';
import { mapState } from 'vuex';
import banner from './components/banner';
import Noempty from 'components/Noempty/Noempty';
import PageUtil from 'utils/PageUtil'
const pageUtil = new PageUtil(externalProd, {
	field: {
		list: 'jdProductArr'
	}
});

export default {
	name: 'onshelf',
	components: {
		ProList,
		banner,
		Noempty
	},
	data() {
		return {
			searchText: '', //搜索内容 v-molde
			hotSearch: null, //热搜
			historySearch: [],
			isShowButton: false,
			isExpand: false,
			overNum: 0,
			goodsDetails: {},
			title: '',
			jdProductArr: [],
			Nomsg: false,
			paging: {
			    loading: false,
			    finished: false,
			    error: false, // 是否错误
			    emptylist: false // 是否显示列表为空时的样式
			}
		};
	},
	computed: {
		...mapState(['themes']),
		jdList() {
			return this.jdProductArr.map(item => {
				item.prodSource = 'JD'
				item.price = item.shopPrice	
				if(!item.selected) { //如果没有上架 则使用京东商品id
					item.prodId = item.jdSkuId
				}
				return item
			})
		}
	},
	async mounted() {
		let { result } = await getAuth()
		// 如果没有权限访问
		if(!result) return this.$router.push('/unAuth')
		pageUtil.loadListByPage(this)
		this.getRecordList();
		if (this.$utils.test.isEmpty(this.themes)) {
			this.getData();
		}
	},
	methods: {
		//获取历史记录
		getRecordList() {
			getHistory().then((res) => {
				this.historySearch = res.result
				this.$nextTick(() => {
					this.calculate();
				});
			})
		},
		calculate() {
			this.historySearch.forEach((item, index) => {
				console.log(this.$refs['history-item' + index] && this.$refs['history-item' + index].length && this.$refs['history-item' + index][0].offsetTop >= (this.$refs['history-item' + index][0].offsetHeight + 10) * 2)
				if(this.$refs['history-item' + index] && this.$refs['history-item' + index].length && this.$refs['history-item' + index][0].offsetTop >= (this.$refs['history-item' + index][0].offsetHeight + 10) * 2) {
					this.overNum++
				}
			})
		},
		// 获取装修楼层数据
		async getData() {
			this.$store
				.dispatch('getBaseSetting')
				.then(res => {
					if (res) {
						this._applyStyle();
						// console.log(this.floorArr)
					}
				})
				.catch(err => {
					console.log(err);
				});
		},
		goback() {
			this.$router.back();
			this.$router.isBack = true;
		},
		//进去搜索列表
		enterSearch(type, searchKey) {
			let searchText = '';
			let queryType = ''
			if (type == 'search') {
				searchText = this.$stringUtils.trim(this.searchText)
			} else {
				searchText = this.$stringUtils.trim(searchKey)
			}
			this.searchText = searchText
			
			// 匹配.html前面的京东id
			let productNum = this.searchText.match(/(\d+)\.html/)
			if (productNum && productNum.length) {// 如果存在则是.html格式 （京东商品链接）
				queryType = 'URL'
			} else if(this.$stringUtils.isNumeric(this.searchText)) { //输入纯数字就是编号
				queryType = 'PROD_NUMBER'
			} else { //其他都是商品名称
				queryType = 'PROD_NAME'
			}
			pageUtil.loadListByPage(this, {key: this.searchText, queryType}, {
				success: (code, res) => {
					if(res.status == -1) {
						this.title = res.msg
					}
				}
			})
			// externalProd({ key: this.searchText, jdSkuId: searchText, pageSize: 15, curPageNO: 1 }).then(res => {
			// 	this.getRecordList();
			// 	if (res.status == 1) {
			// 		this.goodsDetails = res.result[0]
			// 		this.Nomsg = false
			// 	} else {
			// 		this.Nomsg = true
			// 		this.title = res.msg
			// 		this.$toast(res.msg);
			// 	}
			// });
		},
		//清楚历史搜索
		clearKey() {
			this.$dialog
				.confirm({
					title: '是否确认清空历史搜索'
				})
				.then(() => {
					deleteHistory().then(res => {
						if (res.status != 1) {
							this.$toast(res.msg);
							return;
						}
						this.historySearch = [];
					})
				})
				.catch(() => {
					// on cancel
				});
		},
		// 前往商品详情
		goProdDetail(event) {
			this.$router.push({
				path: `${event.selected ? '/goodsDetail' : '/externaDetail'}`,
				query: {
					goodsInfoId: event.prodId
				}
			});
		},
		toPage(name, query) {
			this.$router.push({
				name,
				query
			})
		},
		//加载更多
		onLoad() {
		    pageUtil.loadListByPageMore()
		},
		//设置setTotal
		setTotal(total) {
		    this.total = total
		    if (total == 0) {
		        this.noneResult = true
		    }
		},
		clearInput() {
			this.searchText = ''
		}
	}
};
</script>

<style src="@/assets/css/search.css" scoped></style>
<style src="@/assets/css/onshelf.css" scoped></style>
<style scoped>
.mar {
	margin: 7px 10px 7px 0 !important;
}
.search {
	min-height: 100% !important;
	background: #fff;
}
.hot-search .hot-tit {
	padding: 0;
	font-weight: bold;
}
.hot-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 15px 10px 10px;
}
</style>
